package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;

import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // Optional类可以避免显式的null值判断（null的防御性检查），避免null导致的NPE（NullPointerException）。
        Optional<String> optional = Optional.ofNullable(token);
        // isPresent()一般与.get()方法合用，当optional中存在course时，optional.isPresent()值为true，通过get（）方法返回对象
        if(optional.isPresent()){
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            Integer id = (Integer) claimsBody.get("id");
            //3.存入threadLocal中
            WmUser wmUser = new WmUser();
            wmUser.setId(id);
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        WmThreadLocalUtil.clear();
    }
}
